<?php
/**
 * Discounts row class
 *
 * This row class uses in the model to represent a tax.
 *
 * @access 	public
 * @author 	Valentin
 * @copyright	ResMania 2009 all rights reserved.
 * @version	1.0
 * @link	http://developer.resmania.com/api
 * @since  	08-2009
 */
class RM_Discounts_Row extends RM_Discounts_Row_Abstract {
    /**
     * @var RM_Discounts_Rule
     */
    protected $_rule;

    public function init(){
        parent::init();

        $ruleChunks = explode('_', $this->rule);
        if (count($ruleChunks) == 1) {
            $this->_rule = new RM_Discounts_Rule_All($this, 0);
        } else {
            $ruleClassName = 'RM_Discounts_Rule_'.$ruleChunks[0];
            $this->_rule = new $ruleClassName($this, $ruleChunks[1]);
        }
    }

    /**
     * IMPORTANT! This method only checked intrnal rule matched,
     * to get all discount for a unit (and global) @see RM_Discounts::getByUnit
     *
     * @param RM_Reservation_Details $detail
     * @return void
     */
    public function isMatched(RM_Reservation_Details $detail){
        $parentValue = parent::isMatched($detail);
        if ($parentValue == false) {
            return false;
        }        
        return $this->_rule->isMatched($detail);
    }

    /**
     * We need to delete all unit discounts as weel.
     *
     * @return void
     */
    public function delete(){
        $model = new RM_UnitDiscounts();
        $rows = $model->getByDiscount($this);
        foreach ($rows as $row) {
            $row->delete();
        }
        parent::delete();
    }

    /**
     * Returns the column/value data as an array and parse all assigned units
     * in csv format in 'units' field.
     *
     * @return array
     */
    public function toArray(){
        $dataRow = parent::toArray();
        if ($this->global == 1) {
            $dataRow['units'] = array(0);
        } else {
            $unitDiscountsModel = new RM_UnitDiscounts();
            $unitIDs = array();
            $unitDiscounts = $unitDiscountsModel->getByDiscount($this);
            foreach ($unitDiscounts as $unitDiscount){
                $unitIDs[] = $unitDiscount->unit_id;
            }
            $dataRow['units'] = implode(',', $unitIDs);
        }
        return $dataRow;
    }    
}